package com.anjho.bean;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.AjaxBehaviorEvent;

import com.anjho.dao.DAOAddress;
import com.anjho.dao.DAODistributor;
import com.anjho.exceptions.InvalidDistributorException;
import com.anjho.pojo.Address;
import com.anjho.pojo.City;
import com.anjho.pojo.Distributor;
import com.anjho.pojo.Estate;
import com.anjho.pojo.Neighborhood;
import com.anjho.pojo.PersonType;

@ManagedBean(name = "distributorBean")
@ViewScoped
public class DistributorBean extends GenericBean {

	private static final long serialVersionUID = 1340222169169083861L;
	
	private Distributor distributor;
	private String email;
	private String name;
	private String cnpj;
	private String street;
	private String zip;
	private String neigh;
	private int addNumber;
	private long addCode;
	private String segment;

	private Estate estate;
	private City city;
	private Address address;
	private Neighborhood neighborhood;
	private List<Address> addresses;
	private Boolean addressFound;
	
	private List<Distributor> distributorList;

	public DistributorBean() {
		super();
		this.clearForm();
	}

	public void clearForm() {
		this.setDistributor(new Distributor());
		this.setEstate(new Estate());
		this.setCity(new City());
		this.setNeighborhood(new Neighborhood());
		this.setAddress(new Address());
		this.setAddresses(new ArrayList<Address>());
		this.setDistributorList(new ArrayList<Distributor>());
		this.setStreet("");
		this.setCnpj("");
		this.setEmail("");
		this.setName("");
		this.setSegment("");
		this.setAddressFound(true);
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCnpj() {
		return cnpj;
	}

	public void setCnpj(String cnpj) {
		this.cnpj = cnpj;
	}

	public String getStreet() {
		return street;
	}

	public void setStreet(String street) {
		this.street = street;
	}

	public Distributor getDistributor() {
		return distributor;
	}

	public void setDistributor(Distributor distributor) {
		this.distributor = distributor;
	}

	public String getZip() {
		return zip;
	}

	public void setZip(String zip) {
		this.zip = zip;
	}

	public int getAddNumber() {
		return addNumber;
	}

	public void setAddNumber(int addNumber) {
		this.addNumber = addNumber;
	}

	public List<Address> getAddresses() {
		return addresses;
	}

	public void setAddresses(List<Address> addresses) {
		this.addresses = addresses;
	}

	public Boolean isAddressFound() {
		return addressFound;
	}

	public void setAddressFound(Boolean addressFound) {
		this.addressFound = addressFound;
	}

	public Estate getEstate() {
		return estate;
	}

	public void setEstate(Estate estate) {
		this.estate = estate;
	}

	public City getCity() {
		return city;
	}

	public void setCity(City city) {
		this.city = city;
	}

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

	public Neighborhood getNeighborhood() {
		return neighborhood;
	}

	public void setNeighborhood(Neighborhood neighborhood) {
		this.neighborhood = neighborhood;
	}

	public String getNeigh() {
		return neigh;
	}

	public void setNeigh(String neigh) {
		this.neigh = neigh;
	}

	public List<Distributor> getDistributorList() throws Exception {
		synchronized (this) {
			DAODistributor daoDistributor = new DAODistributor();
			this.distributorList = daoDistributor.getDistributorList();
			return this.distributorList;
		}
	}

	public void setDistributorList(List<Distributor> distributorList) {
		this.distributorList = distributorList;
	}

	public Boolean getAddressFound() {
		return addressFound;
	}

	public long getAddCode() {
		return addCode;
	}

	public void setAddCode(long addCode) {
		this.addCode = addCode;
	}

	public String getSegment() {
		return segment;
	}

	public void setSegment(String segment) {
		this.segment = segment;
	}

	public void selDistChanged(AjaxBehaviorEvent event) {
		try {
			if (this.addCode != 0) {
				DAOAddress daoAddress = new DAOAddress();
				this.address = daoAddress.getAddressByAdCode(this.addCode);
				daoAddress = null;
			} else {
				this.address = new Address();
			}
		} catch (Exception ex) {
			FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro",ex.getMessage());
			FacesContext.getCurrentInstance().addMessage(null, facesMsg);
		}
	}

	public void onSaveClick() throws Exception {
		try {
			DAODistributor daoDistributor = new DAODistributor();
			daoDistributor.update(distributor);
			this.distributor = new Distributor();
		} catch (Exception ex) {
			FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro", ex.getMessage());
			FacesContext.getCurrentInstance().addMessage(null, facesMsg);
		}
	}

	public void onRegisterClick() throws Exception {
		try {
			Distributor aux = new Distributor();
			/*if (!addressFound) {
				Neighborhood neiAux = new Neighborhood();
				neiAux.setCity(this.getCity());
				neiAux.setName(neigh);
				this.getAddress().setNeighborhood(neiAux);
				this.getAddress().setName(street);
			}*/

			aux.getPerson().setAddress(this.getAddress());
			aux.getPerson().setAddressNumber(this.getAddNumber());
			aux.getPerson().setDocument(this.getCnpj().replaceAll("[^0-9]", ""));
			aux.getPerson().setName(this.getName());

			aux.getPerson().setPersonType(new PersonType(2, "Jurídica"));

			// to distributors, this date means the register date.
			aux.getPerson().setBirthDate(Calendar.getInstance().getTime());

			aux.getPerson().setEmail(this.getEmail());
			aux.setSegment(this.getSegment());

			DAODistributor daoDistributor = new DAODistributor();
			daoDistributor.insert(aux);
			daoDistributor = null;
			this.clearForm();
		} catch (Exception ex) {
			FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro", ex.getMessage());
			FacesContext.getCurrentInstance().addMessage(null, facesMsg);
		}
	}

	public void onDeleteClick(ActionEvent actionEvent) {
		try {
			if (this.getDistributor() == null) {
				throw new InvalidDistributorException("É necessário selecionar um distribuidor antes de executar esta operação!");
			}
			DAODistributor daoDistributor = new DAODistributor();
			daoDistributor.delete(this.distributor);
			daoDistributor = null;
		} catch (SQLException ex) {
			FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro na base de dados", ex.getMessage());
			FacesContext.getCurrentInstance().addMessage(null, facesMsg);
		} catch (InvalidDistributorException ex) {
			FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Distribuidor inválido", ex.getMessage());
			FacesContext.getCurrentInstance().addMessage(null, facesMsg);
		} catch (Exception ex) {
			FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro desconhecido", ex.getMessage());
			FacesContext.getCurrentInstance().addMessage(null, facesMsg);
		}
	}

}
